package com.wx.model;

import org.springframework.data.redis.core.script.DefaultRedisScript;

public class RedisScriptTmp{
//	-- 函数：尝试获得红包，如果成功，则返回json字符串，如果不成功，则返回空
//	-- 参数：KEYS[1]红包队列名， KEYS[2]已消费的队列名，KEYS[3]去重的Map名，KEYS[4]用户ID
//	-- 返回值：nil 或者 json字符串，包含用户ID：userId，红包ID：id，红包金额：money
	private static final String tryGetHongBaoScript = ""
			//+"local bConsumed = redis.call('hexists', KEYS[3], KEYS[4]);\n" 
			//+"print('bConsumed:' ,bConsumed);\n"
			+"if redis.call('hexists', KEYS[3], KEYS[4]) ~= 0 then\n"
			+ "return nil\n"
			+ "else\n"
			+ "local hongBao = redis.call('rpop', KEYS[1]);\n"
			//+ "print('hongBao:', hongBao);\n"
			+ "if hongBao then\n"
			+ "local x = cjson.decode(hongBao);\n"
			+ "x['userId'] = KEYS[4];\n"
			+ "local re = cjson.encode(x);\n"
			+ "redis.call('hset', KEYS[3], KEYS[4], KEYS[4]);\n"
			+ "redis.call('lpush', KEYS[2], re);\n"
			+ "return re;\n"
			+ "end\n"
			+ "end\n"
			+ "return nil";
	public static final DefaultRedisScript<String> TryGetHongBaoScript = new DefaultRedisScript<String>(tryGetHongBaoScript, String.class);
	
	
	
//	-- 函数：尝试获得刮刮卡刮奖次数，如果成功，则返回字符串"true"，如果不成功，则返回字符串"false"
//	-- 参数：KEYS[1]用户key，KEYS[2]限制次数
//	-- 返回值："true" "false" 
	private static final String tryGetGGKScript = ""
			//+"local bConsumed = redis.call('hexists', KEYS[3], KEYS[4]);\n" 
			//+"print('bConsumed:' ,bConsumed);\n"
			+ "local countJson = redis.call('get', KEYS[1]);\n"
			+ "if countJson then\n"
			
			+ "local ttls = redis.call('ttl', KEYS[1]); \n"
			+ "local x = cjson.decode(countJson);\n"
			+ " x['count'] = x['count']+1;\n "
			+ "if x['count'] <= tonumber(KEYS[2]) then\n"
			+ "local re = cjson.encode(x);\n"
			+ "redis.call('SETEX',KEYS[1],ttls, re);\n"
			+ "return tostring(true);\n"
			+ "end\n"
			+ "end\n"
			+ "return tostring(false)";
	public static final DefaultRedisScript<String> TryGetGGKScript = new DefaultRedisScript<String>(tryGetGGKScript, String.class);
	
	
//	-- 函数：尝试获得刮刮卡中奖次数，如果成功，则返回字符串"true"，如果不成功，则返回字符串"false"
//	-- 参数：KEYS[1]用户key，KEYS[2]限制次数
//	-- 返回值："true" "false" 
	private static final String GGKScript2 = ""
			+ "local countJson = redis.call('GET', KEYS[1]);\n"
			+ "if countJson then\n"
			+ "local ttls = redis.call('TTL', KEYS[1]); \n"
			+ "local x = cjson.decode(countJson);\n"
			+ "if x['wincount'] then\n"
			+ "else\n"
			+ "return tostring(false);\n"
			+ "end\n"
			+ "x['wincount'] = x['wincount']+1;\n "
			+ "if x['wincount'] <= tonumber(KEYS[2]) then\n"
			+ "local re = cjson.encode(x);\n"
			+ "redis.call('SET',KEYS[1], re);\n"
			+ "if ttls and ttls>0 then\n"
			+ "redis.call('EXPIRE',KEYS[1],ttls);\n"
			+ "end\n"
			+ "return tostring(true);\n"
			+ "end\n"
			+ "end\n"
			+ "return tostring(false)";
	public static final DefaultRedisScript<String> GGKgetCount2Script = new DefaultRedisScript<String>(GGKScript2, String.class);
	
}
